'''
Created on Aug 31, 2011

@author: bstar
'''
import logging
from dopplershift.tx.clients.ftp.client import DSFtpClient
from dopplershift.tx.clients.ftp import events as ftpEvents
logger = logging.getLogger(__name__)

class DSFtpFactory(object):
    ident = None
    def __init__(self,
                 event_manager,
                 host='localhost',
                 port=21,
                 username='user',
                 password='secret',
                 path='/',
                 ):
        
        self._access = {
                        "host": host,
                        "port": port,
                        "username": username,
                        "password": password,
                        "path": path
                        }
        
        self.ident = hash(";".join(map(lambda x: ":".join(map(str, x)), self._access.iteritems())))
        
        self._event_manager = event_manager 
        for el in dir(ftpEvents):
            element = getattr(ftpEvents, el)
            if isinstance(element, str):
                self._event_manager.accept_event(element)
        self._client = DSFtpClient(
                                   upload_callback=self._fileUploaded, 
                                   queue_end_callback=self._uploadingQueueFinished,
                                   upload_errback=self._fileUploadError,
                                   **self._access
                                   )
    def _fileUploadError(self, errInfo):
        logger.debug("File uploading finished with error code %s: %s"%(errInfo.code, errInfo.file))
        self._event_manager.signal(ftpEvents.EVENT_FTP_CLIENT_FILE_UPLOAD_ERROR, errInfo)
    def _fileUploaded(self, filename):
        logger.debug("File uploading finished: %s"%filename)
        self._event_manager.signal(ftpEvents.EVENT_FTP_CLIENT_FILE_UPLOADED, filename)
    def _uploadingQueueFinished(self):
        logger.debug("Uploading queue is finished")
        self._event_manager.signal(ftpEvents.EVENT_FTP_CLIENT_UPLOAD_QUEUE_END, None)
    def send(self, file, priority):
        self._client.send(file, priority)
    def queue(self, fileList):
        self._client.queue(fileList)
    def stop(self):
        self._client.stop()
    def connect(self):
        self._client.connect()
        